package com.zxd.interview.conrruentbook;

import com.zxd.interview.util.date.DateHelper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 定时任务
 * @author Xander
 * @version v1.0.0
 * @Package : com.zxd.interview.cocurrent
 * @Description : 定时任务
 * @Create on : 2023/6/14 20:34
 **/
@Slf4j
public class TimerTest {

    /**
     * 延迟队列
     */
    private static DelayQueue<TimerTask> delayQueue = new DelayQueue<>();
    /**
     * 创建线程池，执行任务
     */
    private static ExecutorService threadPool = Executors.newFixedThreadPool(10);
    /**
     * 定时执行任务的周期频率
     */
    private static final Long INTERVAL = 1000L;

    /**
     * 定时执行任务
     * @param task
     * @param interval
     */
    public void schedule(Runnable task, long interval){
        threadPool.execute(new TimerTask(delayQueue, task, interval));
        threadPool.execute(() -> {
            while (true){
                try {
                    TimerTask timerTask = delayQueue.take();
                    threadPool.execute(timerTask);
                } catch (InterruptedException e) {
                    log.error("执行定时任务抛出了异常");
                }
            }
        });
    }

    public static void main(String[] args){
        new TimerTest().schedule(()-> {
            System.out.println(Thread.currentThread().getName() + " 线程执行任务的当前时间为：" + DateHelper.getNowByNew(DateHelper.yyyyMMdd_hhmmss));
        },INTERVAL);
    }
}
